<?php

namespace App\Repository\Db;

use App\Model\Filter;
use App\Repository\Contracts\SchoolInterface;
use App\Repository\Contracts\UserInterface;
use Illuminate\Support\Facades\DB;
use App\Model\Filter as FilterModel;
use App\Model\School as SchooModel;
use App\Model\SchoolMajorScore as SchoolMajorScoreModel;
use App\Model\SchoolMajor as SchoolMajorModel;

/**
 * @Author:: LuXiang
 * @DateTime: 2017/8/20 20:48
 */
class SchoolRepository extends Repository implements SchoolInterface
{
    protected $rules = [
        'created' => [
            'name' => 'required|min:2|max:16',
            'phone' => 'required|integer',
            'address' => 'required|min:2|max:32',
            'type' => 'required|integer'
        ],
        'updated' => [
            'name' => 'required|min:2|max:16',
            'phone' => 'required|integer',
            'address' => 'required|min:2|max:32',
            'type' => 'required|integer'
        ]
    ];

    protected $messages = [
        'name.required' => "学校名称不能为空",
        'name.min' => "学校名称最少两个字",
        'name.max' => "学校名称最多16个字",
        'phone.required' => "联系电话不能为空",
        'phone.integer' => "联系电话必须是整数",
        'address.required' => "学校地址不能为空",
        'address.min' => "学校名称最少两个字",
        'address.max' => "学校名称最多32个字",
        'type.required' => "学校类别不能为空",
        'type.integer' => "学校类别必须是整数",
    ];

    protected function modelName()
    {
        return 'App\Model\School';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');

        return $this->save($data);
    }

    public function updated($id, array $data)
    {
        $this->validate($data, 'updated');

        return $this->update($data, $id, 'id');
    }

    //学校列表
    public function lists($limit, $page, $map = [], $uid)
    {

        $user = $this->container->make(UserInterface::class)->detail($uid);
        $query = $this->searchMap($map);
      
        $archiveYear = date("Y", strtotime("-2 year"));

        $query = $query->with(['favorite' => function ($query) use ($uid) {
            $query->where('uid', '=', $uid);
        }])->select('school.id', 'school.name', 'school.subject_type', 'school.logo', 'school.is_985', 
        'school.is_211', 'school.comprehensive_rate', 'school.type', 'school.property', 'school.education', 
        'school.province_name', 'school.address', 'school.male_ratio', 'school.female_ratio', 'school.master_point',
        'school.doctoral_point', 'school.master_point', 
        'school_score.min_score', DB::raw('w_school_score.province_name as archive_province'))->leftJoin('school_score', 'school_score.school_id', '=', 'school.id')
            ->where([
                'school_score.year' => $archiveYear,
                'school_score.batch' => 1,
                'school_score.subject' => ($user['subject'] == 1 ? '文科' : '理科'),
                'school_score.province_id' => $user['province_id']
            ])->orderBy('school.comprehensive_rank', 'asc');

      
        $total = $query->count();
        $data = $query->simplePaginate($limit, [
            'school.id', 'school.name', 'school.subject_type', 'school.logo', 'school.is_985', 
            'school.is_211', 'school.comprehensive_rate', 'school.type', 'school.property', 'school.education', 
            'school.province_name', 'school.address', 'school.male_ratio', 'school.female_ratio', 'school.master_point',
            'school.doctoral_point', 'school.master_point', 
            'school_score.min_score', DB::raw('w_school_score.province_name as archive_province')], 'page', $page);

        $list = [];
        foreach ($data as $key => $val) {
            $list[$key]['id'] = $val->id;
            $list[$key]['name'] = $val->name;
            $list[$key]['subject_type'] = $val->subject_type;
            $list[$key]['logo'] = $val->logo;
            $list[$key]['is_985'] = $val->is_985;
            $list[$key]['is_211'] = $val->is_211;
            $list[$key]['comprehensive_rate'] = $val->comprehensive_rate;
            $list[$key]['archive_year'] = $archiveYear;
            $list[$key]['archive_province'] = $val->archive_province;
            $list[$key]['archive_score'] = $val->min_score;
            $list[$key]['archive_probability'] = ($user['score'] > $val->min_score ? '70%' : '40%');
            $list[$key]['type'] = $val->type;
            $list[$key]['property'] = $val->property;
            $list[$key]['education'] = $val->education;
            $list[$key]['province_name'] = $val->province_name;
            $list[$key]['address'] = $val->address;
            $list[$key]['male_ratio'] = $val->male_ratio;
            $list[$key]['female_ratio'] = $val->female_ratio;
            $list[$key]['master_point'] = $val->master_point;
            $list[$key]['doctoral_point'] = $val->doctoral_point;
            $list[$key]['is_favorite'] = $val->favorite->count() ? true : false;
        }

        return $this->simplePaginate('list', $list, $total);
    }

    //学校详情
    public function detail($id, $uid)
    {
        $data = [];
        $query = $this->model->where('id', '=', $id)
            ->with(['favorite' => function ($query) use ($uid) {
                $query->where('uid', '=', $uid);
            }]);
        $detail = $query->first();
        $data = [
            'name' => $detail->name,
            'old_name' => $detail->old_name,
            'logo' => $detail->logo,
            'code' => $detail->code,
            'is_985' => $detail->is_985,
            'is_211' => $detail->is_211,
            'type' => $detail->type,
            'property' => $detail->property,
            'subject_type' => $detail->subject_type,
            'education' => $detail->education,
            'male_ratio' => $detail->male_ratio,
            'female_ratio' => $detail->female_ratio,
            'website' => $detail->website,
            'phone' => $detail->phone,
            'comprehensive_rank' => $detail->comprehensive_rank,
            'founding_year' => $detail->founding_year,
            'address' => $detail->address,
            'introduce' => $detail->introduce,
            'is_favorite' => $detail->favorite->count() ? true : false
        ];
        return $data;
    }

    //院校前年投档线和录取概率
    public function admissions($id, $uid)
    {
        $data = [];
        $schoolInfo = $this->model->find($id);
        $user = $this->container->make(UserInterface::class)->detail($uid);
        $FilterModel = new FilterModel();
        //文理科
        $subject = $FilterModel->get_subject($user['subject']);
        //本科批次
        $batch = $FilterModel->get_property($schoolInfo->property);
        $u_province_id = $user->province_id;
        $dYear = date('Y', time());
        $qYear = date('Y', time()) - 1;
        
        $throwSchoolLine = $this->SchooModel->schoolAdmissions($id, $subject, $u_province_id, $batch, $qYear);
 
        $filingProbability = '0%';
        $filingProbabilityText = '0%';
        if ($throwSchoolLine) {
            $filingProbability = $FilterModel->filingProbability($schoolInfo->province_id, $dYear, $subject, $batch, $user->score, $id, $u_province_id);
        }
        $filingProbabilityText = $FilterModel->getSchoolFilingProbabilityText($filingProbability);
        $data = [
            'throwSchoolLine' => $throwSchoolLine['min_score'],
            'filingProbability' => $filingProbability,
            'filingProbabilityText' => $filingProbabilityText,
        ];
        return $data;
    }

    //院校投档线
    public function filingLine($id, $uid)
    {
        $schoolInfo = $this->model->find($id);
        $user = $this->container->make(UserInterface::class)->detail($uid);
        $FilterModel = new FilterModel();
        //文理科
        $subject = $FilterModel->get_subject($user['subject']);
        //本科批次
        $batch = $FilterModel->get_property($schoolInfo->property);
        $u_province_id = $user->province_id;
        $throwSchoolLineList = $FilterModel->throwSchoolLine($id, $subject, $u_province_id, $batch);
        return $throwSchoolLineList;
    }

    //专业分数线
    public function majorScore($id, $year, $uid)
    {
        $schoolInfo = $this->model->find($id);
        $user = $this->container->make(UserInterface::class)->detail($uid);
        $FilterModel = new FilterModel();
        //文理科
        $subject = $FilterModel->get_subject($user['subject']);
        //本科批次
        $batch = $FilterModel->get_property($schoolInfo->property);

        $detail = $lineSchoolScoreList = $this->model::lineSchoolScoreList($id, $batch, $subject, $year);

        return $detail;
    }
    //院校专业
    public function major($id)
    {
        $data = [];
        $SchoolMajorModel=new SchoolMajorModel();
        $data = $SchoolMajorModel
            ->where('school_id', '=', $id)
            ->get();
        return $data;
    }

    public function filters()
    {
        $list = [];
        $list['type'] = $this->model->groupBy('type')->get(['type'])->toArray();
        $list['subject_type'] = $this->model->where('subject_type', '!=', null)->groupBy('subject_type')->get(['subject_type'])->toArray();
        $list['property'] = $this->model->where('property', '!=', null)->groupBy('property')->get(['property'])->toArray();
        $list['province'] = $this->model->where('province_name', '!=', null)->groupBy('province_name')->get(['province_name'])->toArray();
       
        return $list;
    }


}